package com.example.arcapplication.http;

import android.text.TextUtils;

import com.example.arcapplication.base.BaseViewModel;
import com.example.arcapplication.util.Config;
import com.example.arcapplication.util.Utils;

import java.io.IOException;
import java.lang.ref.WeakReference;

import androidx.annotation.NonNull;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public abstract class ResponseCallback<T> implements Callback<T> {

    private WeakReference<BaseViewModel> contextWeakReference;

    public ResponseCallback(BaseViewModel view, boolean isShowDialog) {
        if (view != null) {
            contextWeakReference = new WeakReference<>(view);
            contextWeakReference.get().getShowDialog().setValue(isShowDialog);
        }
    }

    public ResponseCallback(BaseViewModel view) {
       this(view, true);
    }

    @Override
    public void onResponse(@NonNull Call<T> call, @NonNull Response<T> response) {
        if (contextWeakReference != null && contextWeakReference.get() != null) {
            contextWeakReference.get().getShowDialog().setValue(false);
        }
        Config.LogI( "-->http is onNext");
        ApiException apiException = null;
        if (response.isSuccessful()) {
            onSuccess(response.body());
        } else {
            try {
                assert response.errorBody() != null;
                String string = response.errorBody().string();
                apiException = new ApiException(new Throwable(string), response.code());
            } catch (IOException e) {
                apiException = new ApiException(new Throwable(e.getMessage()), response.code());
            }
        }
        if (apiException != null) {
            onFailure(apiException);
        }
    }

    @Override
    public void onFailure(@NonNull Call<T> call, @NonNull Throwable t) {
        if (contextWeakReference != null && contextWeakReference.get() != null) {
            contextWeakReference.get().getShowDialog().setValue(false);
        }
        ApiException ex = ApiException.handleException(t);
        onFailure(ex);
    }

    public void onFailure(ApiException e) {
        Config.LogI("ApiException err:" + e);
        String message = e.getMessage();
        if(TextUtils.isEmpty(message)){
            return;
        }
        assert message != null;
        if(message.contains("soap:Envelope")){
            message = Utils.analysisFault(message, "faultstring");
        }
        e.setMessage(message);
    }

    public abstract void onSuccess(T o) ;

}
